﻿using log4net;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Windows.Forms;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace PsbUpdate
{
    public partial class Form1 : Form
    {
        private const string DEFAULT_DATABASE_CONNECTION_VALUE = @"Data Source=localhost;Initial Catalog=AdmSekolah;Persist Security Info=True;User ID=sa;Password=123";
        //private string _strConnection;
        public Form1()
        {
            Log.Info("ABSEN APP STARTED");
            InitializeComponent();
            textBox3.Text = DEFAULT_DATABASE_CONNECTION_VALUE;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            using (var da = new SqlDataAdapter("sp_psb_data_nomor_formulir", textBox3.Text))
            {
                da.Fill(dt);
            }
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "NO_FORMULIR";
            comboBox1.ValueMember = "ID";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox4.Text = "ISLAM";
        }

        private bool validateChanges()
        {
            if (_changed)
            {
                var dlg = MessageBox.Show(this, "Ada perubahan data yang belum disimpan. Yakin mau pindah record ?", "Perubahan belum disimpan", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
                if (dlg == DialogResult.Yes)
                {
                    return true;
                }
                return false;
            }
            return true;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (comboBox1.Items.Count < 1)
            {
                return;
            }

            if (comboBox1.SelectedIndex < comboBox1.Items.Count - 1)
            {
                comboBox1.SelectedIndex = comboBox1.SelectedIndex + 1;
            }
            else
            {
                comboBox1.SelectedIndex = 0;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (comboBox1.Items.Count < 1)
            {
                return;
            }

            if (comboBox1.SelectedIndex > 0)
            {
                comboBox1.SelectedIndex = comboBox1.SelectedIndex - 1;
            }
            else
            {
                comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
            }
        }

        bool _changed = false;
        int _prevIndex = -1;

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!validateChanges())
            {
                comboBox1.SelectedIndexChanged -= comboBox1_SelectedIndexChanged;
                comboBox1.SelectedIndex = _prevIndex;
                comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
                return;
            }
            var idFormulir = ((DataRowView)comboBox1.SelectedItem).Row.ItemArray[0].ToString();
            DataTable dt = new DataTable();
            using (var da = new SqlDataAdapter("sp_psb_data_get_data " + idFormulir, textBox3.Text))
            {
                da.Fill(dt);
            }
            clearForm();
            textBox1.Text = dt.Rows[0]["NAMA"].ToString();
            comboBox2.SelectedText = dt.Rows[0]["JENIS_KELAMIN"].ToString();
            textBox2.Text = dt.Rows[0]["TEMPAT_LAHIR"].ToString();
            dateTimePicker1.Value = DateTime.Parse(dt.Rows[0]["TGL_LAHIR"].ToString());
            textBox4.Text = dt.Rows[0]["AGAMA"].ToString();
            textBox5.Text = dt.Rows[0]["ALAMAT"].ToString();
            textBox6.Text = dt.Rows[0]["NAMA_AYAH"].ToString();
            textBox7.Text = dt.Rows[0]["NAMA_IBU"].ToString();
            textBox8.Text = dt.Rows[0]["HP"].ToString();
            checkBox1.Checked = (bool)dt.Rows[0]["YATIM"];
            checkBox2.Checked = (bool)dt.Rows[0]["FORMULIR"];
            checkBox3.Checked = (bool)dt.Rows[0]["AKTA"];
            checkBox4.Checked = (bool)dt.Rows[0]["FOTO"];
            checkBox5.Checked = (bool)dt.Rows[0]["KTP"];
            checkBox6.Checked = (bool)dt.Rows[0]["KK"];

            checkBox2.BackColor = checkBox2.Checked ? System.Drawing.Color.Transparent : System.Drawing.Color.Red;
            checkBox3.BackColor = checkBox3.Checked ? System.Drawing.Color.Transparent : System.Drawing.Color.Red;
            checkBox4.BackColor = checkBox4.Checked ? System.Drawing.Color.Transparent : System.Drawing.Color.Red;
            checkBox5.BackColor = checkBox5.Checked ? System.Drawing.Color.Transparent : System.Drawing.Color.Red;
            checkBox6.BackColor = checkBox6.Checked ? System.Drawing.Color.Transparent : System.Drawing.Color.Red;

            comboBox2.BackColor = string.IsNullOrEmpty(comboBox2.Text) ? System.Drawing.Color.Yellow : System.Drawing.Color.White;
            textBox2.BackColor = string.IsNullOrEmpty(textBox2.Text) ? System.Drawing.Color.Yellow : System.Drawing.Color.White;
            textBox4.BackColor = string.IsNullOrEmpty(textBox4.Text) ? System.Drawing.Color.Yellow : System.Drawing.Color.White;
            textBox5.BackColor = string.IsNullOrEmpty(textBox5.Text) ? System.Drawing.Color.Yellow : System.Drawing.Color.White;
            textBox6.BackColor = string.IsNullOrEmpty(textBox6.Text) ? System.Drawing.Color.Yellow : System.Drawing.Color.White;
            textBox7.BackColor = string.IsNullOrEmpty(textBox7.Text) ? System.Drawing.Color.Yellow : System.Drawing.Color.White;
            textBox8.BackColor = string.IsNullOrEmpty(textBox8.Text) ? System.Drawing.Color.Yellow : System.Drawing.Color.White;

            _changed = false;
            _prevIndex = comboBox1.SelectedIndex;
        }

        private void clearForm()
        {
            textBox1.Text = string.Empty;
            comboBox2.SelectedIndex = -1;
            comboBox2.Text = string.Empty;
            textBox2.Text = string.Empty;
            dateTimePicker1.Value = DateTime.Now;
            textBox4.Text = string.Empty;
            textBox5.Text = string.Empty;
            textBox6.Text = string.Empty;
            textBox7.Text = string.Empty;
            checkBox1.Checked = false;
            textBox8.Text = string.Empty;
            checkBox2.Checked = false;
            checkBox3.Checked = false;
            checkBox4.Checked = false;
            checkBox5.Checked = false;
            checkBox6.Checked = false;

            checkBox2.BackColor = System.Drawing.Color.Transparent;
            checkBox3.BackColor = System.Drawing.Color.Transparent;
            checkBox4.BackColor = System.Drawing.Color.Transparent;
            checkBox5.BackColor = System.Drawing.Color.Transparent;
            checkBox6.BackColor = System.Drawing.Color.Transparent;

            comboBox2.BackColor = System.Drawing.Color.White;
            textBox2.BackColor = System.Drawing.Color.White;
            textBox4.BackColor = System.Drawing.Color.White;
            textBox5.BackColor = System.Drawing.Color.White;
            textBox6.BackColor = System.Drawing.Color.White;
            textBox7.BackColor = System.Drawing.Color.White;
            textBox8.BackColor = System.Drawing.Color.White;

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            _changed = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                var idFormulir = ((DataRowView)comboBox1.SelectedItem).Row.ItemArray[0].ToString();
                string sql = "UPDATE psb_data SET NAMA='{0}', JENIS_KELAMIN='{1}', TEMPAT_LAHIR='{2}', TGL_LAHIR='{3}', AGAMA='{4}',";
                sql += " ALAMAT='{5}', NAMA_AYAH='{6}', NAMA_IBU='{7}', YATIM={8}, HP='{9}',";
                sql += " FORMULIR={10}, AKTA={11}, FOTO={12}, KTP={13}, KK={14}";
                sql += " WHERE id_formulir = {15}";
                sql = string.Format(sql, textBox1.Text.Replace("'", "''"), comboBox2.SelectedItem != null ? comboBox2.SelectedItem.ToString() : string.Empty, textBox2.Text.Replace("'", "''"), dateTimePicker1.Value.ToString("yyyy-MM-dd"), textBox4.Text.Replace("'", "''"),
                    textBox5.Text.Replace("'", "''"), textBox6.Text.Replace("'", "''"), textBox7.Text.Replace("'", "''"), checkBox1.Checked ? "1" : "0", textBox8.Text.Replace("'", "''"), 
                    checkBox2.Checked ? "1" : "0", checkBox3.Checked ? "1" : "0", checkBox4.Checked ? "1" : "0", checkBox5.Checked ? "1" : "0", checkBox6.Checked ? "1" : "0", 
                    idFormulir);

                using (var cn = new SqlConnection(textBox3.Text))
                {
                    cn.Open();
                    var cmd = new SqlCommand(sql, cn);
                    var ra = cmd.ExecuteNonQuery();
                    if (ra > 0)
                    {
                        _changed = false;
                        MessageBox.Show(this, "Data Berhasil di-update");
                    }
                    cmd.Dispose();
                    cn.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Error update data : " + ex.Message);
            }            
        }

        private void comboBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                for (int i = 0; i < comboBox1.Items.Count; i++)
                {
                    //var x = comboBox1.Items[i];
                    var x = ((DataRowView)comboBox1.Items[i]).Row.ItemArray[1].ToString();
                    if (x == comboBox1.Text)
                    {
                        comboBox1.SelectedIndex = i;
                        return;
                    }
                }
                MessageBox.Show(this, "Nomor Formulir "+ comboBox1.Text + " tidak terdaftar.");
            }
        }

        private void Form1_DoubleClick(object sender, EventArgs e)
        {
            textBox3.Visible = !textBox3.Visible;
        }
    }

    public static class Log
    {
        private static ILog log => LogManager.GetLogger(new StackFrame(2).GetMethod().DeclaringType);

        public static void Error(object message) => log.Error(message);

        public static void Error(Exception ex) => log.Error(ex.Message, ex);

        public static void Error(string format, params object[] param) => log.Error(string.Format(format, param));

        public static void Error(Exception ex, string format, params object[] param) => log.Error(string.Format(format, param), ex);

        public static void Info(object message) => log.Info(message);

        public static void Info(string format, params object[] param) => log.InfoFormat(format, param);

        public static void Debug(object message) => log.Debug(message);

        public static void Debug(string format, params object[] param) => log.DebugFormat(format, param);

        public static void Warn(object message) => log.Warn(message);

        public static void Warn(string format, params object[] param) => log.WarnFormat(format, param);
    }
}
